package com.zj.osm.view.homepage

import android.annotation.SuppressLint
import android.content.Context
import android.database.sqlite.SQLiteDatabase.openDatabase
import android.util.Log
import com.zj.osm.App
import com.zj.osm.entity.db.ProjectDao
import com.zj.osm.entity.greendao.*
import com.zj.osm.utils.SQLiteDatabaseUtils
import org.dom4j.Attribute
import org.dom4j.DocumentHelper
import org.dom4j.Element
import java.text.SimpleDateFormat
import java.util.*

/**
 * @ProjectName: OsmDroid
 * @Package: com.zj.osm.view.homepage
 * @Author: jiang zhu
 * @Date: 2019/12/11 16:37
 *
 */
object ZipXmlUtils {

        /**
         * 通过解析出来的xml数据将所有的点保存到数据库。
         *
         * @param str xml数据
         */
    /**
     * 通过解析出来的xml数据将所有的点保存到数据库。
     *
     * @param str xml数据
     */
    fun parseXMLPull(name: String, str: String, path: String, context: Context, xiangmuName: String): Boolean {
        val items = Project()
        val doc = DocumentHelper.parseText(str)
        val projects = doc.rootElement
        val elements = projects.elementIterator()
        try {
            while (elements.hasNext()) {
                val pl = elements.next() as Element
                when (pl.name) {
                    "ProjectId" -> {
                        val projectId = pl.data as String
                        if (isHaveItem(projectId)) {
                            return false
                        } else {
                            @SuppressLint("SimpleDateFormat") val sdf = SimpleDateFormat("yyyy-MM-dd")
                            val c = Calendar.getInstance()
                            c.add(Calendar.DATE, 0)
                            val monday = c.time
                            val preMonday = sdf.format(monday)
                            items.name = xiangmuName
                            items.id = null
                            items.note = ""
                            items.isCheck = true
                            items.time = preMonday
                            items.state = "本地"
                            items.stop = "0"
                            items.voltage = "0.4kV"
                            items.type = "新建"
                            App.getInstances().daoSession.projectDao.insert(items)
                            items.projectId = projectId
                            App.getInstances().daoSession.projectDao.update(items)
                        }
                    }
                    "Point" -> {
                        val attrList = pl.attributes()

                        val points = Point()
                        points.projectId = items.id
                        points.id = null
                        for (i in attrList.indices) {
                            //Point属性的取得
                            val item = attrList[i] as Attribute
                            if (item.name == "Dangjv") {
                                points.dangju = java.lang.Double.parseDouble(item.value)
                            }
                            if (item.name == "Weidu") {
                                points.latitude =item.value.toDouble();
                            }
                            if (item.name == "Jindu") {//3
                                points.longitude = item.value.toDouble();
                            }
                            if (item.name == "LegendTypeKey") {//4
                                points.legendTypeKey = item.value
                            }
                            if (item.name == "Glsb") {//5
                                points.glsb = item.value
                            }
                            if (item.name == "Sbzt") {//6
                                points.state = item.value
                            }
                            if (item.name == "Sbbh") {//7
                                points.mark = item.value
                            }
                            if (item.name == "High") {//8
                                points.high = item.value
                            }
                            if (item.name == "Sblb") {//9
                                points.name = item.value
                            }
                            if (item.name == "Sblx") {//10
                                points.sblx = item.value
                                points.icon = getIconBySblx(item.value, context)//依据设备类型去equipTypye表里面根据name取icon
                            }
                            if (item.name == "Ms") {//11
                                points.note = item.value
                            }
                            if (item.name == "flag") {//12
                                points.mark = item.value
                            }
                            if (item.name == "ID") {//13
                                points.equipType_id = Integer.parseInt(item.value)
                            }
                            if (item.name == "UID") {//14
                                points.uid = item.value
                            }
                            if (item.name == "isT") {//15
                                points.isT = item.value
                            }
                            if (item.name == "Sbbh") {//16
                                points.equipType_name = item.value;
                            }
                            if (item.name == "DefaultLineType") {
                                if (item.value != null && item.value.isNotEmpty()) {
                                    points.defaultLineType = item.value;
                                } else {
                                    points.defaultLineType = getDefaultLineType(points.sblx, context)
                                }
                            }

                        }
                        points.batch = "0"
                        points.whether = "0"
                        App.getInstances().daoSession.pointDao.insert(points)
                        //pointlist.add(pointmap);
                        val Elementspl = pl.elementIterator()
                        while (Elementspl.hasNext()) {
                            val point = Elementspl.next() as Element
                            //Point子节点属性的取得
                            when (point.name) {
                                "ColumnModel" -> {
                                    val equipment = Equipment()
                                    equipment.pointId = points.id
                                    equipment.qubie = 2
                                    equipment.id = null
                                    val ColumnModel = point.attributes()
                                    for (i in ColumnModel.indices) {
                                        val item = ColumnModel[i] as Attribute
                                        if (item.name == "ModuleFL_Name") {//01
                                            equipment.name = item.value
                                        }
                                        if (item.name == "ModuleFL_ID") {//02
                                            equipment.lever_id = item.value
                                        }
                                        if (item.name == "ModuleZL_Name") {//03
                                            equipment.twoName = item.value
                                        }
                                        if (item.name == "ModuleZL_ID") {//04
                                            equipment.head_id = item.value
                                        }
                                        /*if (item.name == "ModuleXH_Name") {
                                            equipment.three_name = item.value
                                        }
                                        if (item.name == "ModuleXH_ID") {
                                            equipment.three_id = item.value
                                        }*/
                                        if (item.name == "Module_Name") {//05
                                            equipment.threeName = item.value
                                        }
                                        if (item.name == "Module_ID") {
                                            equipment.threeId = item.value
                                        }
                                        if (item.name == "Amount") {
                                            equipment.amount = Integer.parseInt(item.value)
                                        }
                                    }
                                    App.getInstances().daoSession.equipmentDao.insert(equipment)
                                }
                                "PointModel" -> {//杆型
                                    val equipment = Equipment()
                                    equipment.pointId = points.id
                                    equipment.qubie = 0
                                    equipment.id = null
                                    val columnModel = point.attributes()
                                    for (i in columnModel.indices) {
                                        val item = columnModel[i] as Attribute
                                        if (item.name == "ModuleFL_Name") {
                                            equipment.name = item.value
                                        }
                                        if (item.name == "ModuleFL_ID") {
                                            equipment.lever_id = item.value
                                        }
                                        if (item.name == "ModuleZL_Name") {
                                            equipment.twoName = item.value
                                        }
                                        if (item.name == "ModuleZL_ID") {
                                            equipment.head_id = item.value
                                        }
                                        if (item.name == "ModuleXH_Name") {//05
                                            equipment.threeName = item.value
                                        }
                                        if (item.name == "Module_ID") {//06
                                            equipment.threeId = item.value
                                        }
                                        if (item.name == "Amount") {//07
                                            equipment.amount = Integer.parseInt(item.value)
                                        }
                                        if (item.name == "Module_Code") {//08
                                            equipment.module_code = item.value
                                        }
                                        if (item.name == "Gangao") {//09
                                            equipment.fourName = item.value
                                        }
                                        if (item.name == "Shaojing") {
                                            equipment.fourId = item.value
                                        }

                                    }
                                    App.getInstances().daoSession.equipmentDao.insert(equipment)
                                }
                                "Multimedia" -> {
                                    val photos =Photos()
                                    photos.points_id = points.id
                                    photos.id = null
                                    val ColumnModel = point.attributes()
                                    for (i in ColumnModel.indices) {
                                        val item = ColumnModel[i] as Attribute
                                        if (item.name == "Multimedia_Path") {
                                            photos.name = item.value
                                            photos.path = "/storage/emulated/0/bhne/" + xiangmuName + "/" + item.value
                                        }
                                    }
                                    App.getInstances().daoSession.photosDao.insert(photos)
                                }
                            }
                        }
                    }
                    "Line" -> {
                        val line = Line()
                        line.projectId = items.id
                        line.item_id=items.id
                        val lineList = pl.attributes()

                        for (i in lineList.indices) {
                            //line属性的取得
                            val item = lineList[i] as Attribute
                            if (item.name == "Start_equip") {//01
                                line.start_id = item.value
                            }
                            if (item.name == "End_equip") {//02
                                line.end_id = item.value
                            }
                            if(item.name=="LineFS_Method"){//03
                                line.path=item.value
                            }
                            if (item.name == "Line_code") {//04
                                line.name = item.value
                            }
                            if (item.name == "LineLen") {//05
                                line.length = item.value
                            }
                            if (item.name == "LineType") {//06
                                line.type = item.value
                            }
                            if (item.name == "Module_ID") {//07
                                line.moduleID = item.value
                            }
                            if (item.name == "Module_Name") {//08
                                line.moduleTxt = item.value
                                line.types = item.value
                            }
                            if (item.name == "LineStatue") {//09
                                line.state = item.value
                            }
                            if (item.name == "LineBackNum") {//10
                                line.backNum = item.value
                            }
                            if (item.name == "LineNum") {//11
                                line.num = item.value
                            }
                            if (item.name == "LineTypeID") {//12
                                line.typeId = item.value
                            }
                            if (item.name == "LineLonB") {//13
                                line.lonB = item.value
                            }
                            if (item.name == "LineLatB") {//14
                                line.latB = item.value
                            }
                            if (item.name == "LineLonA") {//15
                                line.lonA = item.value
                            }
                            if (item.name == "LineLatA") {//16
                                line.latA = item.value
                            }
                            if (item.name == "LineName") {//17
                                line.name = item.value
                            }
                            if (item.name == "LineId") {//18
                                line.cid = item.value
                            }
                            if (item.name == "isT") {//19
                                line.parallelPole = item.value
                            }
                            if (item.name == "LegendTypeKey") {//20
                                line.legendTypeKey = item.value
                            }
                        }
                        //宝哥设置的数据 架空线路 和电缆线路。这个导致查询不到legendTypeKey 。所以这里加入了 type_id两个来保证查询没问题。
                        if (line.legendTypeKey == null || line.legendTypeKey.isEmpty() || line.legendTypeKey == "null") {
                            line.legendTypeKey = getLineRemarker(line.type, line.typeId, context)
                        }
                        App.getInstances().daoSession.lineDao.insert(line)
                        val elementLines = pl.elementIterator()
                        while (elementLines.hasNext()) {
                            val equipment = Equipment()
                            equipment.qubie = 1
                            equipment.id = null
                            val lines = elementLines.next() as Element
                            //Line子节点属性的取得
                            if (lines.name == "LineModel") {
                                val lineModel = lines.attributes()
                                for (i in lineModel.indices) {
                                    val item = lineModel[i] as Attribute
                                    if (item.name == "ModuleFL_Name") {
                                        equipment.name = item.value
                                    }
                                    if (item.name == "ModuleFL_ID") {
                                        equipment.lever_id = item.value
                                    }
                                    if (item.name == "ModuleZL_Name") {
                                        equipment.twoName = item.value
                                    }
                                    if (item.name == "ModuleZL_ID") {
                                        equipment.head_id = item.value
                                    }
                                    if (item.name == "ModuleXH_Name") {
                                        equipment.threeName = item.value
                                    }
                                    if (item.name == "ModuleXH_ID") {
                                        equipment.threeId = item.value
                                    }
                                    if (item.name == "Module_Name") {
                                        equipment.fourName = item.value
                                    }
                                    if (item.name == "Module_ID") {///设备选型编号。
                                        equipment.fourId = item.value
                                    }
                                    if (item.name == "Amount") {
                                        equipment.amount = Integer.parseInt(item.value)
                                    }
                                }
                                equipment.qubie = 1
                                App.getInstances().daoSession.equipmentDao.insert(equipment)
                            }
                        }
                    }
                    "TopographicPoint" -> {
                        val lineList = pl.attributes()
                        val points = Point()
                        points.projectId = items.id
                        points.id = null
                        for (i in lineList.indices) {
                            //line属性的取得
                            val item = lineList[i] as Attribute
                            if (item.name == "name") {
                                points.name = "地形点"
                            }
                            if (item.name == "center_lat") {
                                points.latitude = item.value.toDouble()
                            }
                            if (item.name == "center_lng") {
                                points.longitude = item.value.toDouble()
                            }
                            if (item.name == "address") {
                                points.address = item.value
                            }
                            if (item.name == "LegendTypeKey") {
                                points.legendTypeKey = item.value
                            }
                            if (item.name == "t_length") {
                                points.length = item.value
                            }
                            if (item.name == "t_width") {
                                points.width = item.value
                            }
                            if (item.name == "t_hight") {
                                points.high = item.value
                            }
                            if (item.name == "t_type") {
                                points.sblx = item.value
                            }
                            if (item.name == "equipId") {
                                points.equipType_id = Integer.parseInt(item.value)
                            }
                            if (item.name == "remark") {
                                points.note = item.value
                            }
                            if (item.name == "mark") {
                                points.mark = item.value
                            }
                            if (item.name == "flag") {
                                points.icon = item.value.substring(0, item.value.indexOf("-"))
                                points.legendTypeKey = item.value
                            }
                            if (item.name == "uid") {
                                points.uid = item.value
                            }
                        }
                        points.batch = "0"
                        points.state = "新建"
                        points.whether = "4"
                        App.getInstances().daoSession.pointDao.insert(points)
                    }
                }
            }
            return true
        } catch (e: Exception) {
            //将异常信息打印出来
            e.printStackTrace()
            Log.e("errossss=", e.message.toString())
            return false
        }

    }

    private fun getDefaultLineType(sblx: String?, context: Context): String? {
        var defaultLineTypeName: String? = "1"
        val db = SQLiteDatabaseUtils.getInstance().getSQLiteDatabase();
        assert(db != null)
        @SuppressLint("Recycle")
        val cursor = db!!.rawQuery("select * from EquipType m where m.name ='$sblx'", null)//此处的db是表名，name是列名
        while (cursor.moveToNext()) {
            defaultLineTypeName = cursor.getString(4)

        }

        cursor.close()
        return defaultLineTypeName
    }

    private fun getIconBySblx(value: String?, context: Context): String? {
        var nameIcon: String? = ""
        val db = SQLiteDatabaseUtils.getInstance().getSQLiteDatabase();
        assert(db != null)
        @SuppressLint("Recycle")
        val cursor = db!!.rawQuery("select * from EquipType m where m.name ='$value'", null)//此处的db是表名，name是列名
        while (cursor.moveToNext()) {
            nameIcon = cursor.getString(5)

        }

        cursor.close()
        return nameIcon
    }

    /**
     * 判断当前是否已存在该项目
     */
    private fun isHaveItem(projectId: String?): Boolean {
        val itemsList = App.getInstances().daoSession.projectDao.queryBuilder().orderDesc(ProjectDao.Properties.Id).build().list()
        for (item in itemsList) {
            if (item.projectId == projectId) {
                return true
            }
        }
        return false
    }

    ///查询线的remark
    private fun getLineRemarker(reMarkerName: String, line_typeId: String, context: Context): String {
        Log.e("legengTypeKeee1", reMarkerName)
        var ReMark = ""
        val db = SQLiteDatabaseUtils.getInstance().sqLiteDatabase;
        @SuppressLint("Recycle") val cursor = db.rawQuery("select * from EquipType  where name='$reMarkerName'", null)//此处的db是表名，name是列名
        while (cursor.moveToNext()) {
            ReMark = cursor.getString(6)
            break
        }
        if (ReMark.isEmpty()) {
            @SuppressLint("Recycle") val cursor = db.rawQuery("select * from EquipType  where id='$line_typeId'", null)//此处的db是表名，name是列名
            while (cursor.moveToNext()) {
                ReMark = cursor.getString(6)
                break
            }
        }
        cursor.close()
        return ReMark
    }



}